package com.tsl.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.tsl.reggie.common.BaseContext;
import com.tsl.reggie.common.R;
import com.tsl.reggie.domain.po.ShoppingCart;
import com.tsl.reggie.service.IShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 购物车 前端控制器
 * </p>
 *
 * @author 唐书亮
 * @since 2024-02-28
 */
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private IShoppingCartService shoppingCartService;

    @PostMapping("add")
    public R<ShoppingCart> addShopping(@RequestBody ShoppingCart shoppingCart) {
        //设置用户id
        Long userId = BaseContext.getUserId();
        shoppingCart.setUserId(userId);
        //判断商品是菜品还是套餐

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        if (shoppingCart.getDishId() != null) {
            //菜品
            Long dishId = shoppingCart.getDishId();
            //构造判断是否存在sql语句条件
            queryWrapper.eq(ShoppingCart::getDishId, dishId);


        } else {
            //套餐
            Long setmealId = shoppingCart.getSetmealId();
            queryWrapper.eq(ShoppingCart::getSetmealId, setmealId);
        }
        //判断商是否存在
        ShoppingCart isShoppingCart = shoppingCartService.getOne(queryWrapper);
        //不存在
        if (ObjectUtils.isEmpty(isShoppingCart)) {
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
        } else {
            //存在,直接数量加一
            shoppingCart = isShoppingCart;
            Integer number = shoppingCart.getNumber() + 1;
            shoppingCart.setNumber(number);
            shoppingCartService.updateById(shoppingCart);
        }


        return R.success(shoppingCart);
    }
    //购物车搜索
    @GetMapping("list")
    public R<List<ShoppingCart>> listShoppingCart(){
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getUserId());
        queryWrapper.orderByAsc(ShoppingCart::getCreateTime);

        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);

        return R.success(shoppingCarts);

    }
}
